<?php

class User {
	private $username    = '';
	private $name        = '';
	private $institution = '';
	private $loggedIn    = false;

	function __construct() {
		if (isset($_SESSION['user_logged_in']) && $_SESSION['user_logged_in'] == true) {
			$this->username    = $_SESSION['user_username'];
			$this->name        = $_SESSION['user_name'];
			$this->institution = $_SESSION['user_institution'];
			$this->loggedIn    = true;
		}
	}

	function isLoggedIn() {
		return $this->loggedIn;
	}

	function getName() {
		return $this->name;
	}

	function getInstitution() {
		$inst = explode('-', $this->institution);
		return $inst[0];
	}

	function login($username, $password) {
		global $page_handler;

		if ($this->loggedIn) {
			return true;
		}

		if (strlen($username) < 1 || strlen($password) < 1) {
			return false;
		}

		$data = $page_handler->login($username, $password);

		$xpath_userdata = '/html/body/form/table/tr[2]/td/table/tr[2]/td[2]/table/tr[3]/td/div';
		$data = xPathify($data, $xpath_userdata);

		// Users name is located in 2nd div and institution in the 4th div
		$name = $data->item(1)->nodeValue;
		$inst = $data->item(3)->nodeValue;

		if (strlen($name) > 0) {
			$this->username    = $_SESSION['user_username']    = $username;
			$this->name        = $_SESSION['user_name']        = $name;
			$this->institution = $_SESSION['user_institution'] = $inst;
			$this->loggedIn    = $_SESSION['user_logged_in']   = true;
		}
		else {
			echo ("<h1>Fel login/pass</h1>\n");
		}

		return $this->loggedIn;
	}

	function logout() {
		global $page_handler;

		$data = $page_handler->logout();

		$this->loggedIn = $_SESSION['user_logged_in'] = false;

		session_destroy();

		return true;
	}
}

